from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.permissions import AllowAny
from django.db import transaction
from django.db.models import Q, Count
from django.utils import timezone
from .models import Course
from apps.users.models import User
from .serializers import (
    CourseListSerializer, CourseDetailSerializer,
    CourseCreateUpdateSerializer, TeacherSimpleSerializer
)
from apps.enrollments.serializers import CourseWithEnrollmentSerializer
import logging

logger = logging.getLogger(__name__)


class CourseListView(APIView):
    """课程列表视图"""

    authentication_classes = []
    permission_classes = [AllowAny]

    def get(self, request):
        """获取课程列表"""
        try:
            # 获取查询参数
            page = int(request.GET.get('page', 1))
            page_size = int(request.GET.get('page_size', 10))
            search = request.GET.get('search', '').strip()
            teacher_id = request.GET.get('teacher_id', '')
            semester = request.GET.get('semester', '')
            status_filter = request.GET.get('status', '')

            # 获取当前用户信息
            user_id = request.META.get('HTTP_USER_ID')
            user_role = request.META.get('HTTP_USER_ROLE')

            if not user_id:
                return Response({
                    'code': 401,
                    'message': '未登录'
                }, status=status.HTTP_401_UNAUTHORIZED)

            # 构建查询集
            queryset = Course.objects.select_related('teacher').all()

            # 根据角色过滤数据
            if user_role == 'teacher':
                # 教师只能看到自己的课程
                queryset = queryset.filter(teacher_id=user_id)
            elif user_role == 'student':
                # 学生可以看到所有开放的课程
                queryset = queryset.filter(status='active')
            # 管理员可以看到所有课程

            # 应用过滤条件
            if search:
                queryset = queryset.filter(
                    Q(course_code__icontains=search) |
                    Q(course_name__icontains=search) |
                    Q(teacher__real_name__icontains=search)
                )

            if teacher_id:
                queryset = queryset.filter(teacher_id=teacher_id)

            if semester:
                queryset = queryset.filter(semester=semester)

            if status_filter:
                queryset = queryset.filter(status=status_filter)

            # 排序
            queryset = queryset.order_by('-created_at')

            # 计算总数
            total = queryset.count()

            # 分页
            start = (page - 1) * page_size
            end = start + page_size
            courses = queryset[start:end]

            # 序列化数据 - 统一使用CourseListSerializer
            serializer = CourseListSerializer(courses, many=True)

            response_data = {
                'courses': serializer.data,
                'pagination': {
                    'total': total,
                    'page': page,
                    'page_size': page_size,
                    'total_pages': (total + page_size - 1) // page_size
                }
            }

            return Response({
                'code': 200,
                'message': '获取课程列表成功',
                'data': response_data
            }, status=status.HTTP_200_OK)

        except Exception as e:
            logger.error(f"获取课程列表失败: {str(e)}")
            return Response({
                'code': 500,
                'message': '获取课程列表失败'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    def post(self, request):
        """创建课程"""
        try:
            # 检查权限
            user_role = request.META.get('HTTP_USER_ROLE')
            if user_role not in ['admin', 'teacher']:
                return Response({
                    'code': 403,
                    'message': '权限不足'
                }, status=status.HTTP_403_FORBIDDEN)

            # 如果是教师，只能创建自己的课程
            if user_role == 'teacher':
                user_id = request.META.get('HTTP_USER_ID')
                request.data['teacher'] = int(user_id)

            serializer = CourseCreateUpdateSerializer(data=request.data)
            if not serializer.is_valid():
                return Response({
                    'code': 400,
                    'message': '参数验证失败',
                    'errors': serializer.errors
                }, status=status.HTTP_400_BAD_REQUEST)

            with transaction.atomic():
                course = serializer.save()

            # 返回创建的课程详情
            detail_serializer = CourseDetailSerializer(course)

            return Response({
                'code': 201,
                'message': '创建课程成功',
                'data': detail_serializer.data
            }, status=status.HTTP_201_CREATED)

        except Exception as e:
            logger.error(f"创建课程失败: {str(e)}")
            return Response({
                'code': 500,
                'message': '创建课程失败'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class CourseDetailView(APIView):
    """课程详情视图"""

    authentication_classes = []
    permission_classes = [AllowAny]

    def get(self, request, course_id):
        """获取课程详情"""
        try:
            user_role = request.META.get('HTTP_USER_ROLE')
            user_id = request.META.get('HTTP_USER_ID')

            if not user_id:
                return Response({
                    'code': 401,
                    'message': '未登录'
                }, status=status.HTTP_401_UNAUTHORIZED)

            try:
                course = Course.objects.select_related('teacher').get(id=course_id)
            except Course.DoesNotExist:
                return Response({
                    'code': 404,
                    'message': '课程不存在'
                }, status=status.HTTP_404_NOT_FOUND)

            # 权限检查
            if user_role == 'teacher' and course.teacher_id != int(user_id):
                return Response({
                    'code': 403,
                    'message': '权限不足'
                }, status=status.HTTP_403_FORBIDDEN)

            serializer = CourseDetailSerializer(course)

            return Response({
                'code': 200,
                'message': '获取课程详情成功',
                'data': serializer.data
            }, status=status.HTTP_200_OK)

        except Exception as e:
            logger.error(f"获取课程详情失败: {str(e)}")
            return Response({
                'code': 500,
                'message': '获取课程详情失败'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    def put(self, request, course_id):
        """更新课程"""
        try:
            user_role = request.META.get('HTTP_USER_ROLE')
            user_id = request.META.get('HTTP_USER_ID')

            if user_role not in ['admin', 'teacher']:
                return Response({
                    'code': 403,
                    'message': '权限不足'
                }, status=status.HTTP_403_FORBIDDEN)

            try:
                course = Course.objects.get(id=course_id)
            except Course.DoesNotExist:
                return Response({
                    'code': 404,
                    'message': '课程不存在'
                }, status=status.HTTP_404_NOT_FOUND)

            # 教师只能编辑自己的课程
            if user_role == 'teacher' and course.teacher_id != int(user_id):
                return Response({
                    'code': 403,
                    'message': '只能编辑自己的课程'
                }, status=status.HTTP_403_FORBIDDEN)

            # 如果是教师，不允许修改teacher字段
            if user_role == 'teacher':
                request.data['teacher'] = course.teacher_id

            serializer = CourseCreateUpdateSerializer(course, data=request.data, partial=True)
            if not serializer.is_valid():
                return Response({
                    'code': 400,
                    'message': '参数验证失败',
                    'errors': serializer.errors
                }, status=status.HTTP_400_BAD_REQUEST)

            with transaction.atomic():
                updated_course = serializer.save()

            detail_serializer = CourseDetailSerializer(updated_course)

            return Response({
                'code': 200,
                'message': '更新课程成功',
                'data': detail_serializer.data
            }, status=status.HTTP_200_OK)

        except Exception as e:
            logger.error(f"更新课程失败: {str(e)}")
            return Response({
                'code': 500,
                'message': '更新课程失败'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    def delete(self, request, course_id):
        """删除课程"""
        try:
            user_role = request.META.get('HTTP_USER_ROLE')
            user_id = request.META.get('HTTP_USER_ID')

            if user_role not in ['admin', 'teacher']:
                return Response({
                    'code': 403,
                    'message': '权限不足'
                }, status=status.HTTP_403_FORBIDDEN)

            try:
                course = Course.objects.get(id=course_id)
            except Course.DoesNotExist:
                return Response({
                    'code': 404,
                    'message': '课程不存在'
                }, status=status.HTTP_404_NOT_FOUND)

            # 教师只能删除自己的课程
            if user_role == 'teacher' and course.teacher_id != int(user_id):
                return Response({
                    'code': 403,
                    'message': '只能删除自己的课程'
                }, status=status.HTTP_403_FORBIDDEN)

            # 检查是否有学生选课
            if course.enrolled_count > 0:
                return Response({
                    'code': 400,
                    'message': '该课程已有学生选课，无法删除'
                }, status=status.HTTP_400_BAD_REQUEST)

            with transaction.atomic():
                course.delete()

            return Response({
                'code': 200,
                'message': '删除课程成功'
            }, status=status.HTTP_200_OK)

        except Exception as e:
            logger.error(f"删除课程失败: {str(e)}")
            return Response({
                'code': 500,
                'message': '删除课程失败'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class TeacherListView(APIView):
    """教师列表视图"""

    authentication_classes = []
    permission_classes = [AllowAny]

    def get(self, request):
        """获取教师列表"""
        try:
            user_role = request.META.get('HTTP_USER_ROLE')
            if user_role not in ['admin', 'teacher']:
                return Response({
                    'code': 403,
                    'message': '权限不足'
                }, status=status.HTTP_403_FORBIDDEN)

            # 获取所有激活的教师
            teachers = User.objects.filter(
                role='teacher',
                status='active'
            ).order_by('real_name')

            serializer = TeacherSimpleSerializer(teachers, many=True)

            return Response({
                'code': 200,
                'message': '获取教师列表成功',
                'data': serializer.data
            }, status=status.HTTP_200_OK)

        except Exception as e:
            logger.error(f"获取教师列表失败: {str(e)}")
            return Response({
                'code': 500,
                'message': '获取教师列表失败'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class CourseSemesterListView(APIView):
    """学期列表视图"""

    authentication_classes = []
    permission_classes = [AllowAny]

    def get(self, request):
        """获取学期列表"""
        try:
            # 获取所有存在的学期
            semesters = Course.objects.values_list('semester', flat=True).distinct().order_by('-semester')

            return Response({
                'code': 200,
                'message': '获取学期列表成功',
                'data': list(semesters)
            }, status=status.HTTP_200_OK)

        except Exception as e:
            logger.error(f"获取学期列表失败: {str(e)}")
            return Response({
                'code': 500,
                'message': '获取学期列表失败'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class CourseStatisticsView(APIView):
    """课程统计视图"""

    authentication_classes = []
    permission_classes = [AllowAny]

    def get(self, request):
        """获取课程统计信息"""
        try:
            user_role = request.META.get('HTTP_USER_ROLE')
            user_id = request.META.get('HTTP_USER_ID')

            if not user_id:
                return Response({
                    'code': 401,
                    'message': '未登录'
                }, status=status.HTTP_401_UNAUTHORIZED)

            # 基础查询集
            queryset = Course.objects.all()

            # 根据角色过滤
            if user_role == 'teacher':
                queryset = queryset.filter(teacher_id=user_id)

            # 统计数据
            total_courses = queryset.count()
            active_courses = queryset.filter(status='active').count()
            inactive_courses = queryset.filter(status='inactive').count()
            ended_courses = queryset.filter(status='ended').count()

            # 按状态分组统计
            status_stats = queryset.values('status').annotate(count=Count('id')).order_by('status')

            # 按学期分组统计
            semester_stats = queryset.values('semester').annotate(count=Count('id')).order_by('-semester')

            response_data = {
                'total_courses': total_courses,
                'active_courses': active_courses,
                'inactive_courses': inactive_courses,
                'ended_courses': ended_courses,
                'status_distribution': list(status_stats),
                'semester_distribution': list(semester_stats)
            }

            return Response({
                'code': 200,
                'message': '获取课程统计成功',
                'data': response_data
            }, status=status.HTTP_200_OK)

        except Exception as e:
            logger.error(f"获取课程统计失败: {str(e)}")
            return Response({
                'code': 500,
                'message': '获取课程统计失败'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class CourseStatusUpdateView(APIView):
    """课程状态更新视图"""

    authentication_classes = []
    permission_classes = [AllowAny]

    def patch(self, request, course_id):
        """更新课程状态"""
        try:
            user_role = request.META.get('HTTP_USER_ROLE')
            user_id = request.META.get('HTTP_USER_ID')

            if user_role not in ['admin', 'teacher']:
                return Response({
                    'code': 403,
                    'message': '权限不足'
                }, status=status.HTTP_403_FORBIDDEN)

            try:
                course = Course.objects.get(id=course_id)
            except Course.DoesNotExist:
                return Response({
                    'code': 404,
                    'message': '课程不存在'
                }, status=status.HTTP_404_NOT_FOUND)

            # 教师只能更新自己的课程状态
            if user_role == 'teacher' and course.teacher_id != int(user_id):
                return Response({
                    'code': 403,
                    'message': '只能更新自己的课程状态'
                }, status=status.HTTP_403_FORBIDDEN)

            new_status = request.data.get('status')
            if new_status not in ['active', 'inactive', 'ended']:
                return Response({
                    'code': 400,
                    'message': '无效的状态值'
                }, status=status.HTTP_400_BAD_REQUEST)

            with transaction.atomic():
                course.status = new_status
                course.save(update_fields=['status', 'updated_at'])

            return Response({
                'code': 200,
                'message': '更新课程状态成功'
            }, status=status.HTTP_200_OK)

        except Exception as e:
            logger.error(f"更新课程状态失败: {str(e)}")
            return Response({
                'code': 500,
                'message': '更新课程状态失败'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)